package admin

import (
	"getshop/component/api_io"
	"getshop/models"
	"getshop/models/db_struct"
	redisAdmin "getshop/redis/admin"
	"github.com/astaxie/beego/orm"
	"strconv"
	"time"
)

// 授权管理
type Auth struct {
	App
}

// @Title 运营人员登录
// @Description 运营人员登录
// @Param Account  body string true "登录账号"
// @Param Password body string true "登录密码"
// @Success 0      {Token:string}
// @Failure 50010  请求参数错误
// @Failure 50000 业务错误
// @router /login [post]
func (c *Auth) Login() {
	var data struct {
		Account  string
		Password string
	}
	ok, requestError := api_io.Input(c.Ctx.Input, &data)
	if !ok {
		c.Data["json"] = requestError
		return
	}
	if data.Account == "" {
		c.Data["json"] = api_io.Fail(api_io.ErrParamsEmpty, "请输入登录账号！", nil)
		return
	}
	if data.Password == "" {
		c.Data["json"] = api_io.Fail(api_io.ErrParamsEmpty, "请输入登录密码！", nil)
		return
	}
	o := orm.NewOrm()
	adminModel := models.NewAdmin(o)
	admin := &db_struct.Admin{}
	err := o.QueryTable("Admin").Filter("Account", data.Account).One(admin, "Id", "Status", "Password")
	switch err {
	case nil:
		//用户被注销
		if admin.Status != 1 {
			c.Data["json"] = api_io.Fail(api_io.ErrBusiness, "该账户已经被注销！", nil)
			return
		}
		//用户是否被锁定
		rdsAdmin := redisAdmin.NewAdmin()
		rdsAdmin.Read()
		if rdsAdmin.IsLocking {
			c.Data["json"] = api_io.Fail(api_io.ErrBusiness, "账号已经被锁定！", nil)
			return
		}
		//验证密码
		if admin.Password != adminModel.GeneratePassword(data.Password) {
			tryTimes := 5 //最大尝试次数
			if rdsAdmin.LoginET >= tryTimes-1 {
				c.Data["json"] = api_io.Fail(api_io.ErrBusiness, "账号不存在或密码有误账号已经被锁定1小时！", nil)
				return
			}
			rdsAdmin.LoginET++
			rdsAdmin.Save()
			lastTimes := strconv.Itoa(tryTimes - rdsAdmin.LoginET - 1)
			c.Data["json"] = api_io.Fail(api_io.ErrBusiness, "账号不存在或密码有误，您还能尝试（"+lastTimes+"）次！", nil)
			return
		}
		//登录成功
		rdsAdmin.IsLocking = false
		rdsAdmin.LoginET = 0
		//生成Token
		tokenModel := models.NewAdminAccessToken(o)
		err, token := tokenModel.GenerateToken(admin.Id, 1, time.Now().Unix()+86400)
		rdsAdmin.Token[1] = token
		if err != nil {
			rdsAdmin.Save()
			c.Data["json"] = api_io.Fail(api_io.ErrBusiness, err.Error(), nil)
			return
		}
		rdsAdmin.Save()
		c.Data["json"] = api_io.Success(map[string]string{
			"Token": token,
		}, "登录成功！")
		return
	case orm.ErrNoRows:
		c.Data["json"] = api_io.Fail(api_io.ErrBusiness, "用户名或密码错误！", nil)
		return
	default:
		c.Data["json"] = api_io.Fail(api_io.ErrBusiness, "服务器开小差了~~", nil)
		return
	}
}

// @Title 退出登录
// @Description 退出登录
// @Param Aid   body string true "管理员id"
// @Success 0      {}
// @Failure 50010  请求参数错误
// @router /logout [post]
func (c *Auth) Logout() {
	var data struct {
		Aid int
	}
	ok, requestError := api_io.Input(c.Ctx.Input, &data)
	if !ok {
		c.Data["json"] = requestError
		return
	}
	o := orm.NewOrm()
	_, err := o.QueryTable("AdminAccessToken").Filter("Aid", data.Aid).Filter("AuthTarget", 1).Update(orm.Params{
		"Token": "",
	})
	if err != nil {
		c.Data["json"] = api_io.Fail(api_io.ErrBusiness, err.Error(), nil)
		return
	}
	admin := &redisAdmin.Admin{
		Aid: data.Aid,
	}
	admin.Del()
}
